﻿using CheckIn.UserInfoHost.Applications;
using CheckIn.UserInfoHost.AutoRuns;
using CheckIn.UserInfoHost.Dtos;
using CheckIn.UserInfoHost.Infrastructures;
using Jack.RemoteLog;
using JMS;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Org.BouncyCastle.Asn1.Ocsp;
using Org.BouncyCastle.Crypto;
using System;
using System.Net.Http;
using System.Reflection.Metadata;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using Way.Lib;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace CheckIn.UserInfoHost
{ 
    public class Program
    { 
        public static bool Ready;

        static void test()
        {
            var timestamp = DateTimeOffset.Now.ToUnixTimeSeconds();
            var sn = "fa05fe1e5bcc79b81ad5ad4b58acf787";
            var body = $"{{\"_n\":\"o89QaPVsRu1yppIZzvSZc4\",\"_appid\":\"wxba6223c06417af7b\",\"_timestamp\":{timestamp},\"appid\":\"wxba6223c06417af7b\",\"openid\":\"oEWzBfmdLqhFS2mTXCo2E4Y9gJAM\",\"scene\":0,\"client_ip\":\"127.0.0.1\"}}";
            var add = $"https://api.weixin.qq.com/wxa/getuserriskrank|wxba6223c06417af7b|{timestamp}|{sn}";
            var dataObj = WechatHelper.AesGcmEncryptToBase64_WithTag("otUpngOjU+nVQaWJIC3D/yMLV17RKaP6t4Ot9tbnzLY=", "fmW/zNxXlytUZBgj", body, add);

            var jsonBody = new
            {
                iv = "fmW/zNxXlytUZBgj",
                data = dataObj.result,
                authtag = dataObj.authTag
            };
            var submitBody = jsonBody.ToJsonString();
            var payload = $"https://api.weixin.qq.com/wxa/getuserriskrank\nwxba6223c06417af7b\n{timestamp}\n{submitBody}";

            var private_key_str = "-----BEGIN PRIVATE KEY-----\n" +
              "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDcWhA6Y6Xn8IXm\n" +
              "EXu1rgTMLLYtpTcS7aT0MHBDvcnzYjndLH0sCAzUMfcixiiFFHH8ERJ9t0MjamjC\n" +
              "+vpBgpUgL7hhq/CDuDOFlHFZaZPUeu4QAMJkCCRQK770iX/0U+6K09KgikF3Ts2p\n" +
              "2SRF7zY0E5+spN2GB7/nN3jnt+XsnzVDlVMjE7y++rsVLDuTom2/546NHpJk5Ztt\n" +
              "Q7t/2vhS5SRea90a/bWqKq1o7UQzDi1QIQvNjvczs2kIfdGiuWiaZhfc/qrRWuQM\n" +
              "esITT9AyGYewX7joT4hFwnfC0SPen+Y7VWgKkSFrALVTvbxlRPBY0SKLyE8SFw0B\n" +
              "lMppAxpNAgMBAAECggEBAJe/mn9rkpzJgpzvm1+B6SHnBMsohWYOrNPR6+5q7IIl\n" +
              "Oi477jP9k0Aq7MRQ7STA8MKjyzUymRTxuhXVG7UzxZk14+e3rlo355ttoCXwVHM2\n" +
              "+W2h6D1VchSYG9hyPOE5UAThXaNbszwD1BTNSnKzC4QPo54Up84e1iTYifYiKkCq\n" +
              "F9vJzqCfu5lJZNCyg7qEYFFDsSPH6+DCtvFkpVntRds8cPSU4Q+toDc8f9BR5Qqk\n" +
              "3ArY1dCgHFZxHbzf8fEVICONJKwZIEqwKfAM3nk/YVDQc2LlivBQ1P3X3Q0hdJ7K\n" +
              "BpHLVv4P7IF+b7ITv+pfActkIeyM77a0xJLcoaOWVMECgYEA/0U95g0pm67mO31G\n" +
              "lnBcJz0TsjPtuYzvPCzp26fp1AfTFVVYVWaIYi7Tt6rIHwc1qBex4XOhctXkRDH7\n" +
              "cNoHRsAf5kSkcYkmkBZIu6yKCywVQW5O9MXD6sLmHE5+J0xrr73dJTmlZ4lvTMkX\n" +
              "w9ENondSbCXCli5sXXuxPg8Pqn0CgYEA3PtGWFFIW+CAmOEQyl6Tc4hhauuVE07Y\n" +
              "xVw/uL98Y1MeGvDs4dw0ZGh/nhBnZjRtovvW8c2iRsraadP5xBdj+BcyZwT95XjH\n" +
              "JEZiIgv2cF2uQt6tzjcRg+/568O+DKOLr7LienlwqoetLwX5jMBOTzYm30eB0jYy\n" +
              "99slORJuaBECgYAc08v2s9vUCf9UDoSvLocpozsbL8QT5TeLGyNZu++rEysiSJ4O\n" +
              "HuMd+13LawzofB7yGaLr6+v6lO8PSHm1t9mEguPXVD8h1zQ0p1+VWhnIwzSvS+68\n" +
              "s6y5UUM9RRv4AihTE2Tq9ESamampCTiW03/vrfvv3J/J5/oy4GoWsQq63QKBgH0V\n" +
              "+y646/Wd8g0XsTJsMJkAROyJ57ujMQ8eda91LMroXK0xXVVIGZwQjtSBQpZW7QyJ\n" +
              "85SyKr5ZyyKGa+Y0u1DOiKhJ6hI/uLHu6VOOY/QdAyw08js9bru5VkW/ak+rL8HH\n" +
              "x20+Wqkc3co1XpnurSUnaP+QcYr1RQqJ0NsqdLaRAoGAdnRxjPCH1ieZ9fH2aKYX\n" +
              "ntpBDxoVz3Jp4Pn/cbb5r8Vlwe1jNR0dDs89LfluUPXv82eG6ceG6pqRuBqsf8sg\n" +
              "UwchMJW4ZBPjFLfiQVWMVWGJPdwd9bIFsnoZtC7PMXHP9QoMMp/f843jWTxQ/bQZ\n" +
              "2+a//5zqpCMo9rIwTzV6W6w=\n" +
              "-----END PRIVATE KEY-----";


            var sign = WechatHelper.Sign(private_key_str, payload);

            System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
            client.DefaultRequestHeaders.Add("Wechatmp-Appid", "wxba6223c06417af7b");
            client.DefaultRequestHeaders.Add("Wechatmp-TimeStamp", timestamp.ToString());
            client.DefaultRequestHeaders.Add("Wechatmp-Signature", sign);
            client.DefaultRequestHeaders.Add("Wechatmp-Serial", "证书编号");
            //Wechatmp-Serial
            StringContent stringContent = new StringContent(submitBody, Encoding.UTF8, "application/json");
            var response = client.PostAsync("https://api.weixin.qq.com/wxa/getuserriskrank", stringContent).GetAwaiter().GetResult();
            var txt = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
        }
        static void Main(string[] args)
        {
            //test();
            var builder = new ConfigurationBuilder();
            builder.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
            Run(builder.Build());
        }

        public static void Run(IConfiguration configuration)
        {
            Environment.CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory;
            Global.Configuration = configuration;

            var port = Global.Configuration.GetValue<int>("Port"); //提供微服务的端口
            var serviceAddress = Global.Configuration.GetValue<string>("ServiceAddress");

            //网关地址
            Global.GatewayAddresses = Global.Configuration.GetSection("Gateways").Get<NetAddress[]>();

            ServiceCollection services = InitServices();

            var msp = new MicroServiceHost(services);
            if (string.IsNullOrEmpty(serviceAddress) == false)
            {
                //自定义微服务地址
                msp.ServiceAddress = new NetAddress(serviceAddress, port);
            }

            msp.RegisterScheduleTask<AutoUpdateWechatToken>();

            msp.Register<Controllers.AdminController>("AccountAdminService", "账号服务 - 内部", false);
            msp.Register<Controllers.AccountController>("AccountService", "账号服务", true);
            msp.ServiceProviderBuilded += Msp_ServiceProviderBuilded;
            msp.Build(port, Global.GatewayAddresses, true)
                .Run();
        }

        public static ServiceCollection InitServices()
        {
            ServiceCollection services = new ServiceCollection();
            services.AddSingleton<IConfiguration>(Global.Configuration);
            services.AddScoped<UserInfoDBContext>();

            services.RegisterService();

            services.AddMemoryCache();

            services.AddSingleton<AuthService>();
            services.AddSingleton<WechatService>();
            services.AddHttpClient();

            return services;
        }
        private static void Msp_ServiceProviderBuilded(object sender, IServiceProvider e)
        {
            Global.ServiceProvider = e;
            var logger = e.GetService<ILogger<Program>>();

            //先获取一下token
            e.GetService<WechatService>().GetToken().GetAwaiter().GetResult();
#if DEBUG
            //e.GetService<WechatService>().ImageCheck("https://img2.baidu.com/it/u=2528520711,2512012878&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1722704400&t=35cceea476f65513db9fad599a16fb8d", "oNHAZ7RzpYJWE2YLSF-_0BOChggQ").GetAwaiter().GetResult();

#endif

            using ( var db = new UserInfoDBContext())
            {

            }
            logger.LogInformation("启动完毕");
            Ready = true;
        }
    }
}
